#include <sys/epoll.h>
#include "communicate.h"

#define MAX_EVENTS              3

static void *tpunb_tx_Loop(void *arg)
{
    while (1) 
	{
		if(is_dequeue_start())
		{
			tpunbTxLoop(NULL);
		}
		else
		{
			second_sleep(1);
		}
	}

	return NULL;
}

static void *tpunb_rx_Loop(void *arg)
{
    struct epoll_event ev, events[MAX_EVENTS];
    int nfds, epollfd, n;

    epollfd = epoll_create1(0);
    if (epollfd == -1) 
	{
        DEBUG("epoll_create1 error");
        exit(EXIT_FAILURE);
    }

    ev.events = EPOLLIN;
    ev.data.fd = fd_serial_tpunb;	//"/dev/ttymxc3"
    if (epoll_ctl(epollfd, EPOLL_CTL_ADD, fd_serial_tpunb, &ev) == -1) 
	{
        DEBUG("epoll_ctl: fdWAN error");
        pthread_exit(NULL);
    }

    while (1) 
	{
		if(is_dequeue_start())
		{
			nfds = epoll_wait(epollfd, events, MAX_EVENTS, 2000);
			if (nfds <= 0) 
			{
				//DEBUG("epoll_wait timeout");
				tpunb_data_timeout_callback();
				continue;
			}
			
			for (n = 0; n < nfds; ++n) 
			{
				if (events[n].data.fd == fd_serial_tpunb) 
				{
					if (events[n].events & EPOLLIN) 
					{
						tpunbRxLoop(NULL);	 //处理窄带数据
					}
				}
			}
		}
    }

    DEBUG("exit running......\n");
    pthread_exit(NULL);
}

void tpunb_handler_init(void)
{
	create_thread(tpunb_rx_Loop, NULL);
	create_thread(tpunb_tx_Loop, NULL);
}
